<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 警告 -->
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" align-center :active="activeName-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧导航栏 -->
      <el-form
        :model="ruleFormuser"
        :rules="addRulesForm"
        ref="ruleUserFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeName"
          tab-position="left"
          :before-leave="handleTablevet"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleFormuser.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="goods_price">
              <el-input v-model="ruleFormuser.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="goods_number">
              <el-input v-model="ruleFormuser.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="重量" prop="goods_weight">
              <el-input v-model="ruleFormuser.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="ruleFormuser.goods_cat"
                :options="cateList"
                :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name' }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 遍历数组获取到的参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableDate"
              :key="index"
            >
              <!-- 遍历子参数 attr_vals -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item1"
                  v-for="(item1, index1) in item.attr_vals"
                  :key="index1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 遍历数组获取到的参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableDate"
              :key="index"
            >
              <!-- 遍历子参数 attr_vals -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="actionURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="hedersURL"
              :on-success="handleSuccess"
              width="100px"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor ref="myQuillEditor" v-model="ruleFormuser.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="addGoods">提交按钮</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="addDialogVisibleList" width="50%">
      <span>
        <img :src="previewUrl" alt style="width:100%" />
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeName: '0',
      // 数据双向绑定
      ruleFormuser: {
        goods_name: '',
        goods_cat: [],
        goods_price: 1,
        goods_number: 1,
        goods_weight: 1,
        pics: [],
        // 商品详情
        goods_introduce: '',
        attrs: []
      },
      contentAddList: '',
      // 获取数据的列表
      cateList: [],
      addQueryInfo: {
        query: '',
        pagenum: 2,
        pagesize: 5
      },
      valueCasc: [],
      manyTableDate: [],
      onlyTableDate: [],
      // 上传图片的url地址
      actionURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片的请求头
      hedersURL: {
        Authorization: sessionStorage.getItem('token')
      },
      previewUrl: '',
      fileList: [],
      addDialogVisibleList: false,
      // 验证规则
      addRulesForm: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getAddUserList()
    // 测试代码
    this.activeName = '4'
    this.ruleFormuser.goods_cat = [1, 3, 6]
    this.handleTabClick()
  },
  methods: {
    async getAddUserList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    handleChange () {
      if (this.ruleFormuser.goods_cat.length < 3) {
        this.ruleFormuser.goods_cat = []
      }
    },
    handleTablevet (activeName, oldActiveName) {
      // debugger
      if (this.ruleFormuser.goods_cat.length !== 3 && oldActiveName === '0') {
        return false
      }
    },
    async handleTabClick () {
      if (this.activeName === '1') {
        if (this.cateId === undefined || this.cateId === null) return
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        res.data.forEach((t) => {
          t.attr_vals = t.attr_vals ? t.attr_vals.split(' ') : []
        })
        this.manyTableDate = res.data
      } else if (this.activeName === '2') {
        if (this.cateId === undefined || this.cateId === null) return
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        this.onlyTableDate = res.data
      }
    },
    handlePreview (file) {
      this.previewUrl = file.response.data.url
      this.addDialogVisibleList = true
    },
    handleRemove (file) {
      const path = file.res.data.tmp_path
      const index = this.ruleFormuser.pics.findIndex((t) => t.pic === path)
      this.ruleFormuser.pics.splice(index, 1)
    },
    handleSuccess (res) {
      // console.log(res)
      this.ruleFormuser.pics.push({
        pic: res.data.tmp_path
      })
    },
    addGoods () {
      // console.log(this.ruleFormuser)
      // console.log(this)
      this.$refs.ruleUserFormRef.validate(async (isValue) => {
        if (!isValue) {
          return this.$message({
            message: '表单存在错误',
            type: 'error',
            showClose: true
          })
        }
        // 插件 盛拷贝
        const form = _.cloneDeep(this.ruleFormuser)
        form.goods_cat = form.goods_cat.join(',')
        // 动态参数处理
        this.manyTableDate.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.ruleFormuser.attrs.push(newInfo)
        })
        // 静态参数处理
        this.onlyTableDate.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.ruleFormuser.attrs.push(newInfo)
        })
        // 把值赋值给 form
        form.attrs = this.ruleFormuser.attrs
        console.log(form)
        // 调用接口
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      return this.ruleFormuser.goods_cat.length !== 3
        ? null
        : this.ruleFormuser.goods_cat[2]
    }
  }
}
</script>
<style lang="less" scoped>
.btnAdd {
  margin-top: 15px;
}
</style>
